package com.android.ailaoshan.welcome;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.android.ailaoshan.R;
import com.android.ailaoshan.common.MyNotification;
import com.android.ailaoshan.common.ResourceInfo;

import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.annotations.EverythingIsNonNull;

public class UpLoadService extends Service {



    private final String PIC_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Picture" + File.separator;
    private final String SOUND_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Sound" + File.separator;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate(){

        final int NOTIFICATION_ID = 212;
        final String CHANEL_ID = "START_UPLOAD_FILE";

        MyNotification myNotification = new MyNotification();
        myNotification.createNotificationChanel(CHANEL_ID);
        Notification notification = myNotification.showNotification(R.string.notification_status3,
                R.string.notification_ticker3,CHANEL_ID);

        startForeground(NOTIFICATION_ID,notification);

        MyHandler myHandler = new MyHandler();
        sendFile(myHandler);
    }

    /**
     * 上传文件处理
     */
    private void sendFile(MyHandler myHandler){
        new Thread(
           () -> {
               List<ResourceInfo> resourceInfoList = LitePal
                       .where("upload = ?","2").find(ResourceInfo.class);
               if(resourceInfoList.size() > 0){
                   for(ResourceInfo resourceInfo : resourceInfoList){
                       String filePath;
                       // 图片文件
                       if(resourceInfo.getFileType() == 1){
                           filePath = PIC_PATH + resourceInfo.getName();
                       }else{
                           filePath = SOUND_PATH + resourceInfo.getName();
                       }

                       File file = new File(filePath);
                       if(file.exists()){
                           RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
                           RequestBody requestBody = new MultipartBody.Builder()
                                   .setType(MultipartBody.FORM)
                                   .addFormDataPart("file",resourceInfo.getName(),fileBody)
                                   .addFormDataPart("recordId", String.valueOf(resourceInfo.getId()) )
                                   .addFormDataPart("name", String.valueOf(resourceInfo.getFileNo()) )
                                   .addFormDataPart("fileType", String.valueOf(resourceInfo.getFileType() ) )
                                   .addFormDataPart("date", String.valueOf(resourceInfo.getDate() ) )
                                   .addFormDataPart("protect", String.valueOf(resourceInfo.getProtect() ) )
                                   .addFormDataPart("longitude", String.valueOf(resourceInfo.getLng() ) )
                                   .addFormDataPart("latitude", String.valueOf(resourceInfo.getLat() ))
                                   .addFormDataPart("describe",resourceInfo.getDescribe() )
                                   .build();

                           Request request = new Request.Builder()
                                   .url("http://192.168.1.101:8080/AilaoMIS/appFileUpload")
                                   .post(requestBody)
                                   .build();

                           OkHttpClient okHttpClient = new OkHttpClient();
                           okHttpClient.newCall(request).enqueue(new Callback() {
                               @EverythingIsNonNull
                               @Override
                               public void onFailure(Call call, IOException e) {
                                   e.printStackTrace();

                                   Message notConnectMsg = myHandler.obtainMessage();
                                   notConnectMsg.what = 318;
                                   myHandler.sendMessage(notConnectMsg);
                               }

                               @EverythingIsNonNull
                               @Override
                               public void onResponse(Call call, Response response) throws IOException {
                                   String responseStr = response.body().string();
                                   switch (responseStr){
                                       case "OK":{
                                           onSuccess(resourceInfo);

                                           break;
                                       }
                                       case "EXISTS":{
                                           onSuccess(resourceInfo);

                                           break;
                                       }
                                       case "ERROR":{
                                           break;
                                       }
                                       case "EXCEPTION":{
                                           Message failMsg = myHandler.obtainMessage();
                                           failMsg.what = 318;
                                           myHandler.sendMessage(failMsg);
                                           break;
                                       }
                                   }
                               }
                           });
                       }
                       // 找不到文件，删除记录
                       else{
                           LitePal.deleteAll(ResourceInfo.class,"name = ?",""+resourceInfo.getName());
                       }
                   }
               }
               stopSelf();
           }
        ).start();
    }

    /**
     * 上传文件回调
     */
    private class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg){
            if(msg.what == 318){
                Toast.makeText(UpLoadService.this,"发送文件时服务器状态异常",Toast.LENGTH_SHORT).show();
                stopSelf();
            }
        }
    }

    /**
     * 上传文件成功处理
     */
    private void onSuccess(ResourceInfo resourceInfo){
        resourceInfo.setUpload(1);
        resourceInfo.save();
    }
}
